<?php
declare (strict_types=1);

namespace app\controller;

use Exception;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Request;
use think\Response;

use app\BaseController;
use app\model\User as UserModel;
use app\server\Token as TokenServer;

class Login extends BaseController
{
    protected UserModel $model;

    /**
     * 构造函数
     *
     * @param UserModel $model
     * @param App       $app
     */
    public function __construct(UserModel $model , App $app)
    {
        parent::__construct($app);
        $this->model = $model;
    }

    /**
     * 显示资源列表
     *
     * @param Request $request
     *
     * @return Response
     */
    public function index(Request $request)
    : Response {
        $params = $request->param();
        try {
            $user = $this->model->where('username' , $params['username'])->find();
            if (empty($user)) {
                return $this->error('用户不存在');
            }
            if ($user['password'] !== $params['password']) {
                return $this->error('密码错误');
            }
            $token       = (new TokenServer())->generateToken($user['id']);
            $user->token = $token;

            return $this->success('success' , $user->toArray());
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 获取用户信息
     *
     * @param Request $request
     *
     * @return Response
     */
    public function getInfo(Request $request)
    : Response {
        $token  = $request->param('token');
        $result = (new TokenServer())->checkToken($token);
        if ($result['code'] !== 1) {
            return $this->error($result['msg']);
        }
        $userId = $result['data']->uid;
        try {
            $user = $this->model->find($userId);

            return $this->success('success' , $user->toArray());
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return $this->error($e->getMessage());
        }
    }


}
